package com.liuhengjia.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.liuhengjia.mapper.ArticleMapper;
import com.liuhengjia.pojo.Article;
import com.liuhengjia.pojo.PageBean;
import com.liuhengjia.service.ArticleService;
import com.liuhengjia.util.ThreadLocals;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void insert(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String, Object> decodeMap = ThreadLocals.get();
        Integer id = (Integer) decodeMap.get("id");
        article.setId(id);
        articleMapper.insert(article);
    }

    @Override
    public PageBean<Article> selectPage(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        PageBean<Article> articlePageBean = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> decode = ThreadLocals.get();
        List<Article> articleList = articleMapper.selectPage((Integer) decode.get("id"), categoryId, state);
        Page<Article> articlePage = (Page<Article>) articleList;
        return PageBean.<Article>builder()
                .total(articlePage.getTotal())
                .items(articlePage.getResult())
                .build();
    }
}
